const path = require('path');
// 生成html文件
const HtmlWebpackPlugin = require('html-webpack-plugin');
// 压缩，webpack5内置
const TerserPlugin = require('terser-webpack-plugin');
// css压缩
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');

module.exports = {
  mode: 'production',
  // mode: 'development',
  // 方便查看打包后的源代码
  // devtool: 'source-map'（行列都有）|'cheap-source-map'（只有行没有列）|'hidden-source-map'（在产物里不通过//#指明，但是会生成source-map，一般开发环境如果要使用就用这种，source-map就传到内部服务器），不填等同于false
  devtool: 'hidden-source-map',
  entry: './src/index.js',
  output: {
    filename: '[name].[contenthash].js',
    path: path.resolve(__dirname, 'html'),
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
    },
    extensions: ['.js', '.json'],
  },
  // 优化压缩
  optimization: {
    minimize: true, // 启用压缩
    minimizer: [
      // js压缩
      new TerserPlugin({
        terserOptions: {
          compress: {
            drop_console: true, // 去除 console
            drop_debugger: true, // 去除 debugger
          },
          format: {
            comments: false, // 去除注释
          },
        },
        extractComments: false, // 不将注释提取到单独的文件中
      }),
      // css压缩
      new CssMinimizerPlugin(),
    ],
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(png|jpg|jpeg|gif)$/,
        type: 'asset/resource',
      },
      // 添加 babel-loader 配置
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'],
          },
        },
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'webpackTest',
      // template: './index.html',
    }),
    // gzip压缩
    new CompressionPlugin({
      test: /\.(js|css|html|svg)$/, // 只压缩这些文件
      exclude: /\.(png|jpg|gif)$/, // 排除图片等已压缩的文件
      algorithm: 'gzip',
      threshold: 10240, // 10kb 以下文件不压缩
    }),
  ],
  devServer: {
    port: 8080,
    open: true,
  },
};
